/**
 * Konva画板类库
 * 提供手写板、绘图、文字编辑等功能
 */
class KonvaBoard {
    constructor(containerId, options = {}) {
        this.containerId = containerId;
        this.options = {
            width: 800,
            height: 600,
            backgroundColor: 'white',
            maxHistorySize: 50,
            ...options
        };
        
        // 初始化变量
        this.stage = null;
        this.layer = null;
        this.backgroundLayer = null;
        this.eraserLayer = null;
        this.currentTool = 'brush';
        this.isDrawing = false;
        this.isErasing = false;
        this.isSelecting = false;
        this.currentColor = '#000000';
        this.currentBrushSize = 5;
        this.polygonPoints = [];
        this.polygonLine = null;
        this.selectionRect = null;
        this.selectedShapes = [];
        this.history = [];
        this.historyIndex = -1;
        this.shapeIdCounter = 0;
        this.textElements = [];
        this.currentTextInput = null;
        this.isTextEditing = false;
        this.eraserPath = null;
        this.eraserTrail = [];
        
        // 事件回调
        this.eventCallbacks = {
            onToolChange: null,
            onColorChange: null,
            onBrushSizeChange: null,
            onHistoryChange: null
        };
        
        this.init();
    }
    
    /**
     * 初始化画板
     */
    init() {
        this.initCanvas();
        this.bindEvents();
        this.initKeyboardShortcuts();
    }
    
    /**
     * 初始化画布
     */
    initCanvas() {
        const container = document.getElementById(this.containerId);
        if (!container) {
            throw new Error(`Container with id "${this.containerId}" not found`);
        }
        
        // 计算画布尺寸
        let canvasWidth = this.options.width;
        let canvasHeight = this.options.height;
        
        // 移动端适配
        if (window.innerWidth <= 768) {
            canvasWidth = Math.min(window.innerWidth - 20, this.options.width);
            canvasHeight = Math.min(window.innerHeight * 0.6, this.options.height);
        }
        
        this.stage = new Konva.Stage({
            container: this.containerId,
            width: canvasWidth,
            height: canvasHeight
        });
        
        // 背景层
        this.backgroundLayer = new Konva.Layer();
        this.stage.add(this.backgroundLayer);
        
        // 绘制层
        this.layer = new Konva.Layer();
        this.stage.add(this.layer);
        
        // 初始化橡皮擦层
        this.initEraserLayer();
        
        // 添加背景
        const background = new Konva.Rect({
            x: 0,
            y: 0,
            width: canvasWidth,
            height: canvasHeight,
            fill: this.options.backgroundColor
        });
        this.backgroundLayer.add(background);
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => this.handleResize());
    }
    
    /**
     * 初始化橡皮擦层
     */
    initEraserLayer() {
        this.eraserLayer = new Konva.Layer();
        this.stage.add(this.eraserLayer);
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        this.stage.on('mousedown touchstart', (e) => this.onMouseDown(e));
        this.stage.on('mousemove touchmove', (e) => this.onMouseMove(e));
        this.stage.on('mouseup touchend', (e) => this.onMouseUp(e));
        this.stage.on('click', (e) => this.onMouseClick(e));
        this.stage.on('dblclick', (e) => this.onMouseDoubleClick(e));
        
        // 点击画布空白区域时隐藏文字控制按钮
        this.stage.on('click', (e) => {
            if (e.target === this.stage && this.currentTool !== 'text') {
                this.hideAllTextControls();
            }
        });
        
        // 移动端优化
        this.stage.on('touchstart', (e) => e.evt.preventDefault());
        this.stage.on('touchmove', (e) => e.evt.preventDefault());
    }
    
    /**
     * 处理窗口大小变化
     */
    handleResize() {
        if (!this.stage) return;
        
        let canvasWidth = this.options.width;
        let canvasHeight = this.options.height;
        
        if (window.innerWidth <= 768) {
            canvasWidth = Math.min(window.innerWidth - 20, this.options.width);
            canvasHeight = Math.min(window.innerHeight * 0.6, this.options.height);
        }
        
        this.stage.width(canvasWidth);
        this.stage.height(canvasHeight);
        
        const background = this.backgroundLayer.children[0];
        if (background) {
            background.width(canvasWidth);
            background.height(canvasHeight);
        }
        
        this.stage.batchDraw();
    }
    
    /**
     * 设置工具
     */
    setTool(tool) {
        this.currentTool = tool;
        
        // 重置状态
        this.isDrawing = false;
        this.isErasing = false;
        this.isSelecting = false;
        this.isTextEditing = false;
        this.polygonPoints = [];
        
        if (this.polygonLine) {
            this.polygonLine.destroy();
            this.polygonLine = null;
        }
        
        if (this.selectionRect) {
            this.selectionRect.destroy();
            this.selectionRect = null;
        }
        
        // 清除选中状态
        this.selectedShapes.forEach(shape => {
            if (shape.originalStroke) {
                shape.stroke(shape.originalStroke);
                shape.strokeWidth(shape.originalStrokeWidth);
            }
        });
        this.selectedShapes = [];
        
        // 隐藏所有文字控制按钮
        this.hideAllTextControls();
        
        this.stage.draggable(false);
        
        // 触发回调
        if (this.eventCallbacks.onToolChange) {
            this.eventCallbacks.onToolChange(tool);
        }
    }
    
    /**
     * 设置颜色
     */
    setColor(color) {
        this.currentColor = color;
        if (this.eventCallbacks.onColorChange) {
            this.eventCallbacks.onColorChange(color);
        }
    }
    
    /**
     * 设置画笔粗细
     */
    setBrushSize(size) {
        this.currentBrushSize = size;
        if (this.eventCallbacks.onBrushSizeChange) {
            this.eventCallbacks.onBrushSizeChange(size);
        }
    }
    
    /**
     * 生成形状ID
     */
    generateShapeId() {
        return 'shape_' + (++this.shapeIdCounter);
    }
    
    /**
     * 保存操作记录
     */
    saveAction(action) {
        this.history = this.history.slice(0, this.historyIndex + 1);
        this.history.push(action);
        this.historyIndex++;
        
        if (this.history.length > this.options.maxHistorySize) {
            this.history.shift();
            this.historyIndex--;
        }
        
        if (this.eventCallbacks.onHistoryChange) {
            this.eventCallbacks.onHistoryChange(this.history.length, this.historyIndex);
        }
    }
    
    /**
     * 撤销
     */
    undo() {
        if (this.historyIndex > 0) {
            const action = this.history[this.historyIndex];
            this.historyIndex--;
            this.applyHistoryAction(action, true);
        }
    }
    
    /**
     * 重做
     */
    redo() {
        if (this.historyIndex < this.history.length - 1) {
            this.historyIndex++;
            const action = this.history[this.historyIndex];
            this.applyHistoryAction(action, false);
        }
    }
    
    /**
     * 清空画布
     */
    clearCanvas() {
        const shapesData = [];
        this.layer.children.forEach(shape => {
            shapesData.push(shape.toJSON());
        });
        
        this.hideAllTextControls();
        this.layer.destroyChildren();
        if (this.eraserLayer) {
            this.eraserLayer.destroyChildren();
        }
        
        this.textElements = [];
        this.layer.batchDraw();
        
        this.saveAction({
            type: 'clear_canvas',
            shapesData: shapesData
        });
    }
    
    /**
     * 获取当前工具
     */
    getCurrentTool() {
        return this.currentTool;
    }
    
    /**
     * 获取当前颜色
     */
    getCurrentColor() {
        return this.currentColor;
    }
    
    /**
     * 获取当前画笔粗细
     */
    getCurrentBrushSize() {
        return this.currentBrushSize;
    }
    
    /**
     * 获取历史记录状态
     */
    getHistoryState() {
        return {
            canUndo: this.historyIndex > 0,
            canRedo: this.historyIndex < this.history.length - 1,
            historyLength: this.history.length,
            historyIndex: this.historyIndex
        };
    }
    
    /**
     * 设置事件回调
     */
    on(event, callback) {
        if (this.eventCallbacks.hasOwnProperty(event)) {
            this.eventCallbacks[event] = callback;
        }
    }
    
    /**
     * 销毁画板
     */
    destroy() {
        if (this.stage) {
            this.stage.destroy();
        }
        window.removeEventListener('resize', this.handleResize);
    }
    
    // ==================== 绘图相关方法 ====================
    
    /**
     * 鼠标按下事件
     */
    onMouseDown(e) {
        const pos = this.stage.getPointerPosition();
        if (!pos) return;
        
        switch (this.currentTool) {
            case 'brush':
                this.isDrawing = true;
                const brushLine = new Konva.Line({
                    id: this.generateShapeId(),
                    points: [pos.x, pos.y],
                    stroke: this.currentColor,
                    strokeWidth: this.currentBrushSize,
                    lineCap: 'round',
                    lineJoin: 'round',
                    tension: 0.5
                });
                this.layer.add(brushLine);
                break;
                
            case 'eraser':
                this.isErasing = true;
                this.eraseAt(pos);
                break;
                
            case 'select':
                this.isSelecting = true;
                const startPos = pos;
                this.selectionRect = new Konva.Rect({
                    x: startPos.x,
                    y: startPos.y,
                    width: 0,
                    height: 0,
                    stroke: '#00ff00',
                    strokeWidth: 2,
                    dash: [5, 5]
                });
                this.layer.add(this.selectionRect);
                break;
        }
    }
    
    /**
     * 鼠标移动事件
     */
    onMouseMove(e) {
        const pos = this.stage.getPointerPosition();
        if (!pos) return;
        
        if (this.isDrawing && this.currentTool === 'brush') {
            const lastLine = this.layer.children[this.layer.children.length - 1];
            const newPoints = lastLine.points().concat([pos.x, pos.y]);
            lastLine.points(newPoints);
            this.layer.batchDraw();
        }
        
        if (this.isErasing && this.currentTool === 'eraser') {
            this.eraserTrail.push(pos);
            if (this.eraserTrail.length > 10) {
                this.eraserTrail.shift();
            }
            
            this.eraseAt(pos);
            
            for (let i = 0; i < this.eraserTrail.length - 1; i++) {
                const start = this.eraserTrail[i];
                const end = this.eraserTrail[i + 1];
                const steps = Math.ceil(Math.sqrt((end.x - start.x) ** 2 + (end.y - start.y) ** 2) / 2);
                
                for (let j = 1; j < steps; j++) {
                    const t = j / steps;
                    const interpPos = {
                        x: start.x + (end.x - start.x) * t,
                        y: start.y + (end.y - start.y) * t
                    };
                    this.eraseAt(interpPos);
                }
            }
        }
        
        if (this.isSelecting && this.currentTool === 'select' && this.selectionRect) {
            const startPos = this.selectionRect.position();
            this.selectionRect.width(pos.x - startPos.x);
            this.selectionRect.height(pos.y - startPos.y);
            this.layer.batchDraw();
        }
    }
    
    /**
     * 鼠标抬起事件
     */
    onMouseUp(e) {
        if (this.isDrawing) {
            const lastLine = this.layer.children[this.layer.children.length - 1];
            if (lastLine && lastLine.points().length > 2) {
                this.saveAction({
                    type: 'add_shape',
                    shapeId: lastLine.id(),
                    shapeData: lastLine.toJSON()
                });
            }
        }
        
        if (this.isErasing && this.eraserPath) {
            const pathId = this.generateShapeId();
            this.eraserPath.id(pathId);
            this.saveAction({
                type: 'eraser_action',
                pathId: pathId,
                pathData: this.eraserPath.toJSON()
            });
            this.resetEraserPath();
        }
        
        if (this.isSelecting && this.currentTool === 'select' && this.selectionRect) {
            this.findSelectedShapes();
        }
        
        this.isDrawing = false;
        this.isErasing = false;
        this.isSelecting = false;
    }
    
    /**
     * 鼠标点击事件
     */
    onMouseClick(e) {
        const pos = this.stage.getPointerPosition();
        
        if (this.currentTool === 'polygon') {
            if (pos) {
                this.addPolygonPoint(pos);
            }
        } else if (this.currentTool === 'text') {
            if (pos) {
                const clickedText = this.findClickedText(pos);
                if (clickedText) {
                    this.showTextControls(clickedText);
                } else {
                    this.createTextInput(pos);
                }
            }
        }
    }
    
    /**
     * 鼠标双击事件
     */
    onMouseDoubleClick(e) {
        if (this.currentTool === 'polygon' && this.polygonPoints.length >= 3) {
            this.completePolygon();
        }
    }
    
    /**
     * 橡皮擦功能
     */
    eraseAt(pos) {
        const eraserSize = this.currentBrushSize * 2;
        
        if (!this.eraserPath) {
            this.eraserPath = new Konva.Line({
                points: [pos.x, pos.y],
                stroke: 'white',
                strokeWidth: eraserSize * 2,
                lineCap: 'round',
                lineJoin: 'round',
                tension: 0.5
            });
            this.eraserLayer.add(this.eraserPath);
        } else {
            const points = this.eraserPath.points();
            points.push(pos.x, pos.y);
            this.eraserPath.points(points);
        }
    }
    
    /**
     * 重置橡皮擦路径
     */
    resetEraserPath() {
        this.eraserPath = null;
    }
    
    /**
     * 添加多边形顶点
     */
    addPolygonPoint(pos) {
        this.polygonPoints.push(pos);
        
        if (this.polygonLine) {
            this.polygonLine.destroy();
        }
        
        const points = [];
        this.polygonPoints.forEach(point => {
            points.push(point.x, point.y);
        });
        
        this.polygonLine = new Konva.Line({
            points: points,
            stroke: this.currentColor,
            strokeWidth: this.currentBrushSize,
            closed: false
        });
        this.layer.add(this.polygonLine);
        this.layer.batchDraw();
    }
    
    /**
     * 完成多边形
     */
    completePolygon() {
        if (this.polygonPoints.length >= 3) {
            const points = [];
            this.polygonPoints.forEach(point => {
                points.push(point.x, point.y);
            });
            
            const polygon = new Konva.Line({
                id: this.generateShapeId(),
                points: points,
                stroke: this.currentColor,
                strokeWidth: this.currentBrushSize,
                closed: true,
                fill: this.currentColor + '40'
            });
            
            this.layer.add(polygon);
            this.polygonLine.destroy();
            this.polygonLine = null;
            this.polygonPoints = [];
            this.layer.batchDraw();
            
            this.saveAction({
                type: 'add_shape',
                shapeId: polygon.id(),
                shapeData: polygon.toJSON()
            });
        }
    }
    
    /**
     * 绘制预设图形
     */
    drawPresetShape(shapeType) {
        const centerX = this.stage.width() / 2;
        const centerY = this.stage.height() / 2;
        const size = Math.min(this.stage.width(), this.stage.height()) * 0.15;
        let points = [];
        
        switch (shapeType) {
            case 'square':
                points = [
                    centerX - size/2, centerY - size/2,
                    centerX + size/2, centerY - size/2,
                    centerX + size/2, centerY + size/2,
                    centerX - size/2, centerY + size/2
                ];
                break;
                
            case 'triangle':
                points = [
                    centerX, centerY - size/2,
                    centerX - size/2, centerY + size/2,
                    centerX + size/2, centerY + size/2
                ];
                break;
                
            case 'star':
                points = this.generateStarPoints(centerX, centerY, size);
                break;
                
            case 'circle':
                const circle = new Konva.Circle({
                    id: this.generateShapeId(),
                    x: centerX,
                    y: centerY,
                    radius: size/2,
                    stroke: this.currentColor,
                    strokeWidth: this.currentBrushSize,
                    fill: this.currentColor + '40'
                });
                this.layer.add(circle);
                this.layer.batchDraw();
                
                this.saveAction({
                    type: 'add_shape',
                    shapeId: circle.id(),
                    shapeData: circle.toJSON()
                });
                return;
        }
        
        const shape = new Konva.Line({
            id: this.generateShapeId(),
            points: points,
            stroke: this.currentColor,
            strokeWidth: this.currentBrushSize,
            closed: true,
            fill: this.currentColor + '40'
        });
        
        this.layer.add(shape);
        this.layer.batchDraw();
        
        this.saveAction({
            type: 'add_shape',
            shapeId: shape.id(),
            shapeData: shape.toJSON()
        });
    }
    
    /**
     * 生成五角星的点
     */
    generateStarPoints(centerX, centerY, size) {
        const points = [];
        const outerRadius = size / 2;
        const innerRadius = outerRadius * 0.4;
        const numPoints = 5;
        
        for (let i = 0; i < numPoints * 2; i++) {
            const angle = (i * Math.PI) / numPoints;
            const radius = i % 2 === 0 ? outerRadius : innerRadius;
            const x = centerX + radius * Math.cos(angle - Math.PI / 2);
            const y = centerY + radius * Math.sin(angle - Math.PI / 2);
            points.push(x, y);
        }
        
        return points;
    }
    
    /**
     * 查找选中的形状
     */
    findSelectedShapes() {
        if (!this.selectionRect) return;
        
        const selectionBounds = {
            x: this.selectionRect.x(),
            y: this.selectionRect.y(),
            width: this.selectionRect.width(),
            height: this.selectionRect.height()
        };
        
        if (selectionBounds.width < 0) {
            selectionBounds.x += selectionBounds.width;
            selectionBounds.width = Math.abs(selectionBounds.width);
        }
        if (selectionBounds.height < 0) {
            selectionBounds.y += selectionBounds.height;
            selectionBounds.height = Math.abs(selectionBounds.height);
        }
        
        this.selectedShapes = [];
        const shapes = this.layer.children.slice();
        
        shapes.forEach(shape => {
            if ((shape instanceof Konva.Line || shape instanceof Konva.Circle) && shape !== this.selectionRect) {
                let isSelected = false;
                
                if (shape instanceof Konva.Line) {
                    const points = shape.points();
                    for (let i = 0; i < points.length; i += 2) {
                        const x = points[i];
                        const y = points[i + 1];
                        
                        if (x >= selectionBounds.x && x <= selectionBounds.x + selectionBounds.width &&
                            y >= selectionBounds.y && y <= selectionBounds.y + selectionBounds.height) {
                            isSelected = true;
                            break;
                        }
                    }
                } else if (shape instanceof Konva.Circle) {
                    const circleX = shape.x();
                    const circleY = shape.y();
                    const radius = shape.radius();
                    
                    const closestX = Math.max(selectionBounds.x, Math.min(circleX, selectionBounds.x + selectionBounds.width));
                    const closestY = Math.max(selectionBounds.y, Math.min(circleY, selectionBounds.y + selectionBounds.height));
                    
                    const distance = Math.sqrt((circleX - closestX) ** 2 + (circleY - closestY) ** 2);
                    if (distance <= radius) {
                        isSelected = true;
                    }
                }
                
                if (isSelected) {
                    this.selectedShapes.push(shape);
                    shape.originalStroke = shape.stroke();
                    shape.originalStrokeWidth = shape.strokeWidth();
                    shape.stroke('#ff0000');
                    shape.strokeWidth(shape.strokeWidth() + 2);
                }
            }
        });
        
        this.layer.batchDraw();
    }
    
    /**
     * 删除选中的形状
     */
    deleteSelectedShapes() {
        const deletedShapes = [];
        
        this.selectedShapes.forEach(shape => {
            deletedShapes.push({
                shapeId: shape.id(),
                shapeData: shape.toJSON()
            });
            shape.destroy();
        });
        
        this.selectedShapes = [];
        
        if (this.selectionRect) {
            this.selectionRect.destroy();
            this.selectionRect = null;
        }
        
        this.layer.batchDraw();
        
        deletedShapes.forEach(item => {
            this.saveAction({
                type: 'remove_shape',
                shapeId: item.shapeId,
                shapeData: item.shapeData
            });
        });
    }
    
    /**
     * 初始化键盘快捷键
     */
    initKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
                e.preventDefault();
                this.undo();
            }
            if ((e.ctrlKey || e.metaKey) && e.key === 'y') {
                e.preventDefault();
                this.redo();
            }
            if ((e.ctrlKey || e.metaKey) && e.key === 'z' && e.shiftKey) {
                e.preventDefault();
                this.redo();
            }
        });
        
        // 移动端优化
        document.addEventListener('touchstart', (e) => {
            if (e.touches.length > 1) {
                e.preventDefault();
            }
        }, { passive: false });
        
        document.addEventListener('touchend', (e) => {
            const now = Date.now();
            const lastTouch = document.lastTouch || 0;
            const timeDiff = now - lastTouch;
            
            if (timeDiff < 300 && timeDiff > 0) {
                e.preventDefault();
            }
            document.lastTouch = now;
        }, { passive: false });
    }
    
    /**
     * 应用历史操作
     */
    applyHistoryAction(action, isUndo) {
        switch (action.type) {
            case 'add_shape':
                if (isUndo) {
                    this.removeShapeById(action.shapeId);
                } else {
                    this.addShapeFromData(action.shapeData);
                }
                break;
                
            case 'remove_shape':
                if (isUndo) {
                    this.addShapeFromData(action.shapeData);
                } else {
                    this.removeShapeById(action.shapeId);
                }
                break;
                
            case 'clear_canvas':
                if (isUndo) {
                    this.restoreShapesFromData(action.shapesData);
                } else {
                    this.clearAllShapes();
                }
                break;
                
            case 'eraser_action':
                if (isUndo) {
                    this.removeEraserPath(action.pathId);
                } else {
                    this.addEraserPath(action.pathData);
                }
                break;
                
            case 'add_text':
                if (isUndo) {
                    this.removeTextById(action.textId);
                } else {
                    this.addTextFromData(action.textData);
                }
                break;
                
            case 'remove_text':
                if (isUndo) {
                    this.addTextFromData(action.textData);
                } else {
                    this.removeTextById(action.textId);
                }
                break;
                
            case 'edit_text':
                if (isUndo) {
                    this.restoreTextData(action.textId, action.originalData);
                } else {
                    this.restoreTextData(action.textId, action.newData);
                }
                break;
        }
    }
    
    /**
     * 形状管理函数
     */
    addShapeFromData(shapeData) {
        const shape = Konva.Node.create(shapeData);
        this.layer.add(shape);
        this.layer.batchDraw();
    }
    
    removeShapeById(shapeId) {
        const shape = this.layer.findOne('#' + shapeId);
        if (shape) {
            shape.destroy();
            this.layer.batchDraw();
        }
    }
    
    clearAllShapes() {
        this.layer.destroyChildren();
        this.layer.batchDraw();
    }
    
    restoreShapesFromData(shapesData) {
        shapesData.forEach(shapeData => {
            const shape = Konva.Node.create(shapeData);
            this.layer.add(shape);
        });
        this.layer.batchDraw();
    }
    
    addEraserPath(pathData) {
        const path = Konva.Node.create(pathData);
        this.eraserLayer.add(path);
        this.eraserLayer.batchDraw();
    }
    
    removeEraserPath(pathId) {
        const path = this.eraserLayer.findOne('#' + pathId);
        if (path) {
            path.destroy();
            this.eraserLayer.batchDraw();
        }
    }
    
    // ==================== 文字相关方法 ====================
    
    /**
     * 查找点击的文字元素
     */
    findClickedText(pos) {
        const stagePos = this.stage.getPointerPosition();
        if (!stagePos) return null;
        
        const textNodes = this.layer.find('Text');
        
        for (let textNode of textNodes) {
            const textRect = textNode.getClientRect();
            
            if (stagePos.x >= textRect.x && stagePos.x <= textRect.x + textRect.width &&
                stagePos.y >= textRect.y && stagePos.y <= textRect.y + textRect.height) {
                return textNode;
            }
        }
        return null;
    }
    
    /**
     * 创建文字输入框
     */
    createTextInput(pos) {
        this.hideAllTextControls();
        
        const stageRect = this.stage.container().getBoundingClientRect();
        
        const textContainer = document.createElement('div');
        textContainer.className = 'text-input-overlay';
        
        const inputLeft = stageRect.left + pos.x - 2;
        const inputTop = stageRect.top + pos.y - 2;
        
        textContainer.style.left = inputLeft + 'px';
        textContainer.style.top = inputTop + 'px';
        textContainer.style.width = '100px';
        textContainer.style.height = '20px';
        
        const textInput = document.createElement('input');
        textInput.type = 'text';
        textInput.placeholder = '输入文字...';
        textInput.value = '';
        textInput.style.fontSize = '16px';
        textInput.style.fontFamily = 'Microsoft YaHei';
        textInput.style.color = this.currentColor;
        
        textContainer.appendChild(textInput);
        document.body.appendChild(textContainer);
        
        textInput.focus();
        
        this.currentTextInput = textContainer;
        this.isTextEditing = true;
        
        let isFinishing = false;
        
        textInput.addEventListener('blur', () => {
            if (!isFinishing) {
                isFinishing = true;
                this.finishTextInput();
            }
        });
        
        textInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !isFinishing) {
                isFinishing = true;
                this.finishTextInput();
            } else if (e.key === 'Escape' && !isFinishing) {
                isFinishing = true;
                this.cancelTextInput();
            }
        });
        
        textInput.addEventListener('input', () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            ctx.font = '16px Microsoft YaHei';
            const textWidth = ctx.measureText(textInput.value || textInput.placeholder).width;
            const newWidth = Math.max(100, textWidth + 20);
            textContainer.style.width = newWidth + 'px';
        });
    }
    
    /**
     * 完成文字输入
     */
    finishTextInput() {
        if (!this.currentTextInput) return;
        
        const textInput = this.currentTextInput.querySelector('input');
        const text = textInput.value.trim();
        
        if (text) {
            const stageRect = this.stage.container().getBoundingClientRect();
            
            const textX = parseInt(this.currentTextInput.style.left) - stageRect.left + 2;
            const textY = parseInt(this.currentTextInput.style.top) - stageRect.top + 2;
            
            const textNode = new Konva.Text({
                id: this.generateShapeId(),
                x: textX,
                y: textY,
                text: text,
                fontSize: 16,
                fontFamily: 'Microsoft YaHei',
                fill: this.currentColor,
                draggable: true
            });
            
            this.addTextEventListeners(textNode);
            
            this.layer.add(textNode);
            this.layer.batchDraw();
            
            this.textElements.push({
                id: textNode.id(),
                element: textNode,
                data: textNode.toJSON()
            });
            
            this.saveAction({
                type: 'add_text',
                textId: textNode.id(),
                textData: textNode.toJSON()
            });
        }
        
        if (this.currentTextInput && this.currentTextInput.parentNode) {
            document.body.removeChild(this.currentTextInput);
        }
        this.currentTextInput = null;
        this.isTextEditing = false;
    }
    
    /**
     * 取消文字输入
     */
    cancelTextInput() {
        if (this.currentTextInput && this.currentTextInput.parentNode) {
            document.body.removeChild(this.currentTextInput);
            this.currentTextInput = null;
            this.isTextEditing = false;
        }
    }
    
    /**
     * 显示文字控制按钮
     */
    showTextControls(textNode) {
        this.hideAllTextControls();
        
        textNode.draggable(true);
        
        const textRect = textNode.getClientRect();
        
        const borderRect = new Konva.Rect({
            x: textRect.x - 2,
            y: textRect.y - 2,
            width: textRect.width + 4,
            height: textRect.height + 4,
            stroke: '#999',
            strokeWidth: 2,
            cornerRadius: 3,
            fill: 'transparent',
            listening: false
        });
        
        const deleteBtn = new Konva.Circle({
            x: textRect.x - 15,
            y: textRect.y + textRect.height / 2,
            radius: 12,
            fill: '#dc3545',
            stroke: '#c82333',
            strokeWidth: 1
        });
        
        const deleteText = new Konva.Text({
            x: textRect.x - 15 - 6,
            y: textRect.y + textRect.height / 2 - 8,
            text: '×',
            fontSize: 16,
            fill: 'white',
            fontFamily: 'Arial'
        });
        
        const editBtn = new Konva.Circle({
            x: textRect.x + textRect.width + 15,
            y: textRect.y + textRect.height / 2,
            radius: 12,
            fill: '#007bff',
            stroke: '#0056b3',
            strokeWidth: 1
        });
        
        const editText = new Konva.Text({
            x: textRect.x + textRect.width + 15 - 6,
            y: textRect.y + textRect.height / 2 - 8,
            text: '✎',
            fontSize: 14,
            fill: 'white',
            fontFamily: 'Arial'
        });
        
        deleteBtn.on('click', (e) => {
            e.cancelBubble = true;
            this.deleteTextNode(textNode);
        });
        deleteText.on('click', (e) => {
            e.cancelBubble = true;
            this.deleteTextNode(textNode);
        });
        
        editBtn.on('click', (e) => {
            e.cancelBubble = true;
            this.editTextNode(textNode);
        });
        editText.on('click', (e) => {
            e.cancelBubble = true;
            this.editTextNode(textNode);
        });
        
        this.layer.add(borderRect);
        this.layer.add(deleteBtn);
        this.layer.add(deleteText);
        this.layer.add(editBtn);
        this.layer.add(editText);
        
        textNode.controlsContainer = { 
            borderRect, 
            deleteBtn, 
            deleteText, 
            editBtn, 
            editText 
        };
        
        if (!textNode._hasDragListeners) {
            textNode.on('dragmove', () => {
                if (textNode.controlsContainer) {
                    this.updateTextControlsPosition(textNode);
                }
            });
            
            textNode.on('dragend', () => {
                if (textNode.controlsContainer) {
                    this.updateTextControlsPosition(textNode);
                }
            });
            
            textNode._hasDragListeners = true;
        }
        
        textNode.moveToTop();
        this.layer.batchDraw();
    }
    
    /**
     * 更新文字控制元素位置
     */
    updateTextControlsPosition(textNode) {
        if (!textNode.controlsContainer) return;
        
        const textRect = textNode.getClientRect();
        
        if (textNode.controlsContainer.borderRect) {
            textNode.controlsContainer.borderRect.x(textRect.x - 2);
            textNode.controlsContainer.borderRect.y(textRect.y - 2);
            textNode.controlsContainer.borderRect.width(textRect.width + 4);
            textNode.controlsContainer.borderRect.height(textRect.height + 4);
        }
        
        if (textNode.controlsContainer.deleteBtn) {
            textNode.controlsContainer.deleteBtn.x(textRect.x - 15);
            textNode.controlsContainer.deleteBtn.y(textRect.y + textRect.height / 2);
        }
        
        if (textNode.controlsContainer.deleteText) {
            textNode.controlsContainer.deleteText.x(textRect.x - 15 - 6);
            textNode.controlsContainer.deleteText.y(textRect.y + textRect.height / 2 - 8);
        }
        
        if (textNode.controlsContainer.editBtn) {
            textNode.controlsContainer.editBtn.x(textRect.x + textRect.width + 15);
            textNode.controlsContainer.editBtn.y(textRect.y + textRect.height / 2);
        }
        
        if (textNode.controlsContainer.editText) {
            textNode.controlsContainer.editText.x(textRect.x + textRect.width + 15 - 6);
            textNode.controlsContainer.editText.y(textRect.y + textRect.height / 2 - 8);
        }
        
        this.layer.batchDraw();
    }
    
    /**
     * 隐藏所有文字控制按钮
     */
    hideAllTextControls() {
        this.textElements.forEach(item => {
            if (item.element.controlsContainer) {
                if (item.element.controlsContainer.borderRect) {
                    item.element.controlsContainer.borderRect.destroy();
                }
                if (item.element.controlsContainer.deleteBtn) {
                    item.element.controlsContainer.deleteBtn.destroy();
                }
                if (item.element.controlsContainer.deleteText) {
                    item.element.controlsContainer.deleteText.destroy();
                }
                if (item.element.controlsContainer.editBtn) {
                    item.element.controlsContainer.editBtn.destroy();
                }
                if (item.element.controlsContainer.editText) {
                    item.element.controlsContainer.editText.destroy();
                }
                item.element.controlsContainer = null;
            }
        });
        this.layer.batchDraw();
    }
    
    /**
     * 编辑文字
     */
    editTextNode(textNode) {
        if (textNode.controlsContainer) {
            if (textNode.controlsContainer.borderRect) {
                textNode.controlsContainer.borderRect.destroy();
            }
            if (textNode.controlsContainer.deleteBtn) {
                textNode.controlsContainer.deleteBtn.destroy();
            }
            if (textNode.controlsContainer.deleteText) {
                textNode.controlsContainer.deleteText.destroy();
            }
            if (textNode.controlsContainer.editBtn) {
                textNode.controlsContainer.editBtn.destroy();
            }
            if (textNode.controlsContainer.editText) {
                textNode.controlsContainer.editText.destroy();
            }
            textNode.controlsContainer = null;
            this.layer.batchDraw();
        }
        
        const textRect = textNode.getClientRect();
        const stagePos = this.stage.container().getBoundingClientRect();
        
        const editContainer = document.createElement('div');
        editContainer.className = 'text-input-overlay';
        
        const editLeft = stagePos.left + textRect.x - 2;
        const editTop = stagePos.top + textRect.y - 2;
        
        editContainer.style.left = editLeft + 'px';
        editContainer.style.top = editTop + 'px';
        editContainer.style.width = (textRect.width + 4) + 'px';
        editContainer.style.height = (textRect.height + 4) + 'px';
        
        const editInput = document.createElement('input');
        editInput.type = 'text';
        editInput.value = textNode.text();
        editInput.style.fontSize = textNode.fontSize() + 'px';
        editInput.style.fontFamily = textNode.fontFamily();
        editInput.style.color = textNode.fill();
        
        editContainer.appendChild(editInput);
        document.body.appendChild(editContainer);
        
        editInput.focus();
        editInput.select();
        
        this.currentTextInput = editContainer;
        this.isTextEditing = true;
        
        let isFinishing = false;
        
        editInput.addEventListener('blur', () => {
            if (!isFinishing) {
                isFinishing = true;
                this.finishTextEdit(textNode, editInput.value);
            }
        });
        
        editInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !isFinishing) {
                isFinishing = true;
                this.finishTextEdit(textNode, editInput.value);
            } else if (e.key === 'Escape' && !isFinishing) {
                isFinishing = true;
                this.cancelTextEdit();
            }
        });
        
        editInput.addEventListener('input', () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            ctx.font = textNode.fontSize() + 'px ' + textNode.fontFamily();
            const textWidth = ctx.measureText(editInput.value).width;
            const newWidth = Math.max(textRect.width, textWidth + 20);
            editContainer.style.width = (newWidth + 4) + 'px';
        });
    }
    
    /**
     * 完成文字编辑
     */
    finishTextEdit(textNode, newText) {
        if (!this.currentTextInput) return;
        
        const trimmedText = newText.trim();
        if (trimmedText) {
            const originalData = textNode.toJSON();
            
            textNode.text(trimmedText);
            this.layer.batchDraw();
            
            const textElement = this.textElements.find(item => item.id === textNode.id());
            if (textElement) {
                textElement.data = textNode.toJSON();
            }
            
            this.saveAction({
                type: 'edit_text',
                textId: textNode.id(),
                originalData: originalData,
                newData: textNode.toJSON()
            });
        }
        
        if (this.currentTextInput && this.currentTextInput.parentNode) {
            document.body.removeChild(this.currentTextInput);
        }
        this.currentTextInput = null;
        this.isTextEditing = false;
    }
    
    /**
     * 取消文字编辑
     */
    cancelTextEdit() {
        if (this.currentTextInput && this.currentTextInput.parentNode) {
            document.body.removeChild(this.currentTextInput);
            this.currentTextInput = null;
            this.isTextEditing = false;
        }
    }
    
    /**
     * 删除文字
     */
    deleteTextNode(textNode) {
        if (textNode.controlsContainer) {
            if (textNode.controlsContainer.borderRect) {
                textNode.controlsContainer.borderRect.destroy();
            }
            if (textNode.controlsContainer.deleteBtn) {
                textNode.controlsContainer.deleteBtn.destroy();
            }
            if (textNode.controlsContainer.deleteText) {
                textNode.controlsContainer.deleteText.destroy();
            }
            if (textNode.controlsContainer.editBtn) {
                textNode.controlsContainer.editBtn.destroy();
            }
            if (textNode.controlsContainer.editText) {
                textNode.controlsContainer.editText.destroy();
            }
            textNode.controlsContainer = null;
            this.layer.batchDraw();
        }
        
        const textData = textNode.toJSON();
        
        textNode.destroy();
        this.layer.batchDraw();
        
        this.textElements = this.textElements.filter(item => item.id !== textNode.id());
        
        this.saveAction({
            type: 'remove_text',
            textId: textNode.id(),
            textData: textData
        });
    }
    
    /**
     * 添加文字事件监听器
     */
    addTextEventListeners(textNode) {
        textNode.on('click', (e) => {
            if (this.currentTool === 'text') {
                e.cancelBubble = true;
                this.showTextControls(textNode);
            }
        });
        
        textNode.on('mouseenter', () => {
            if (this.currentTool === 'text') {
                document.body.style.cursor = 'pointer';
            }
        });
        
        textNode.on('mouseleave', () => {
            if (this.currentTool === 'text') {
                document.body.style.cursor = 'default';
            }
        });
        
        textNode.on('dragmove', () => {
            if (textNode.controlsContainer) {
                this.updateTextControlsPosition(textNode);
            }
        });
        
        textNode.on('dragend', () => {
            if (textNode.controlsContainer) {
                this.updateTextControlsPosition(textNode);
            }
        });
    }
    
    /**
     * 文字管理函数
     */
    addTextFromData(textData) {
        const textNode = Konva.Node.create(textData);
        
        textNode.draggable(true);
        
        this.addTextEventListeners(textNode);
        
        this.layer.add(textNode);
        
        this.textElements.push({
            id: textNode.id(),
            element: textNode,
            data: textData
        });
        
        this.layer.batchDraw();
    }
    
    removeTextById(textId) {
        const textNode = this.layer.findOne('#' + textId);
        if (textNode) {
            if (textNode.controlsContainer) {
                if (textNode.controlsContainer.borderRect) {
                    textNode.controlsContainer.borderRect.destroy();
                }
                if (textNode.controlsContainer.deleteBtn) {
                    textNode.controlsContainer.deleteBtn.destroy();
                }
                if (textNode.controlsContainer.deleteText) {
                    textNode.controlsContainer.deleteText.destroy();
                }
                if (textNode.controlsContainer.editBtn) {
                    textNode.controlsContainer.editBtn.destroy();
                }
                if (textNode.controlsContainer.editText) {
                    textNode.controlsContainer.editText.destroy();
                }
                textNode.controlsContainer = null;
            }
            
            textNode.destroy();
            
            this.textElements = this.textElements.filter(item => item.id !== textId);
            
            this.layer.batchDraw();
        }
    }
    
    restoreTextData(textId, textData) {
        const textNode = this.layer.findOne('#' + textId);
        if (textNode) {
            textNode.setAttrs(textData);
            
            const textElement = this.textElements.find(item => item.id === textId);
            if (textElement) {
                textElement.data = textData;
            }
            
            this.layer.batchDraw();
        }
    }
    
    /**
     * 获取选中的形状
     */
    getSelectedShapes() {
        return this.selectedShapes;
    }
    
    /**
     * 获取文字元素
     */
    getTextElements() {
        return this.textElements;
    }
    
    /**
     * 导出画布数据
     */
    exportData() {
        return {
            shapes: this.layer.children.map(child => child.toJSON()),
            textElements: this.textElements.map(item => item.data),
            history: this.history,
            historyIndex: this.historyIndex
        };
    }
    
    /**
     * 导入画布数据
     */
    importData(data) {
        this.clearCanvas();
        
        if (data.shapes) {
            data.shapes.forEach(shapeData => {
                this.addShapeFromData(shapeData);
            });
        }
        
        if (data.textElements) {
            data.textElements.forEach(textData => {
                this.addTextFromData(textData);
            });
        }
        
        if (data.history) {
            this.history = data.history;
            this.historyIndex = data.historyIndex || this.history.length - 1;
        }
    }
}
